import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

class Listener implements Runnable {
	
	private User user = null;
	private ChatFrame cFrame = null;
	
	public Listener(User user, ChatFrame cFrame) {
		this.user = user;
		this.cFrame = cFrame;
		new Thread(this, user.getName()+"").start();
	}
	
	@SuppressWarnings("resource")
	@Override
	public void run() {
		DatagramSocket serverSocket = null;
		try {
			serverSocket = new DatagramSocket(user.getPort());
		} catch (SocketException e) {
			e.printStackTrace();
		}
		byte[] receiveData = new byte[1024];
		while (true) {
			DatagramPacket receivePacket = new DatagramPacket(receiveData,
					receiveData.length);
			try {
				serverSocket.receive(receivePacket);
			} catch (IOException e) {
				e.printStackTrace();
			}
			ObjectInputStream in;
			Message msg = null;
			try {
				in = new ObjectInputStream(new ByteArrayInputStream(receiveData)); 
				msg = (Message) in.readObject();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			if (msg instanceof AckMessage) {
				cFrame.addQueue((AckMessage)msg);
			} else {
				try {
					if (Configuration.getInstance().getOrdering().equalsIgnoreCase("total")) {
						if (msg instanceof TotalMessage) {
							((TotalMessage) msg).reverseSender();
							cFrame.totalDeliver((TotalMessage) msg);
						}
					} else {
						cFrame.bDeliver((NormalMessage)msg);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				new Sender(new AckMessage(msg.getSenderID()), ((NormalMessage)msg).getSender(), cFrame.getQueue());
			}
		}
		
	}
}